﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

namespace SimpleSocxs.manage
{
    public partial class streams : AuthorizedPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            phError.Visible = false;
            phSuccess.Visible = false;
        }

        protected void OnUpdateStream(object sender, EventArgs args) 
        {
            var stream_id = int.Parse(((IButtonControl)sender).CommandArgument);
            var stream = SocxsDataStore.Current.GetStreamByID(stream_id);
            stream.Extract();
        }

        protected void OnDeleteStream(object sender, EventArgs args)
        {
            var stream_id = int.Parse(((IButtonControl)sender).CommandArgument);
            SocxsDataStore.Current.DeleteStream(stream_id);
        }

        protected void OnFindSocialStream(object sender, EventArgs args)
        {
            var btn = (Button)sender;
            var stream_type = btn.CommandArgument;
            var username = ((TextBox)btn.Parent.FindControl("txt" + stream_type + "Username")).Text;
            var stream = new SocialStream {Url = username, StreamType = (StreamType)Enum.Parse(typeof(StreamType), stream_type) };

            Session["findstream"] = stream;
            var result = stream.Extract(username);

            if (result.Success)
            {
                phSuccess.Visible = true;
                gvSocialResult.DataSource = result.ConvertedData;
            }
            else
            {
                phError.Visible = true;
                var sbuf = new StringBuilder();
                
                if(!string.IsNullOrEmpty(result.ReturnedData))
                    sbuf.AppendLine("Response: \n" + result.ReturnedData);
                if(result.Error != null)
                    sbuf.Append("Exception: \n" + result.Error);

                txtError.Value = sbuf.ToString();                
            }
        }

        protected void OnAddStream(object sender, EventArgs args)
        {
            var stream = Session["findstream"] as SocialStream;
            if (stream == null)
                return;
            stream.Name = txtStreamName.Text;
            SocxsDataStore.Current.AddStream(SocxsUser.ID, stream);
            Session["findstream"] = null;
        }        

        protected void Page_PreRender(object sender, EventArgs args)
        {
            rptStreams.DataSource = SocxsDataStore.Current.GetAllUserStreams(SocxsUser.ID);
            DataBind();
        }
    }
}